from PyQt5.QtWidgets import QWidget, QApplication, QLabel,QSizePolicy
from PyQt5.QtCore import QRect, Qt, QPoint,QSize
from PyQt5.QtGui import QImage, QPixmap, QPainter, QPen, QGuiApplication, QPainterPath, QPolygon, QBrush

class DrawBoxLabel(QLabel):
    def __init__(self, parent=None):
        super(DrawBoxLabel, self).__init__(parent)
        self.shapeType = 'polygon'  # 默认为矩形，可以是'line', 'rectangle', 'polygon'
        self.Line_list = [0, 0, 0, 0]
        self.Rectangle_list = [0, 0, 0, 0]
        self.Polygon_list = []
        self.originalPixmap = None  # 保存原始图片的pixmap
        self.isEnabledDrawing = False  # 控制是否启用画图功能
        self.setCursor(Qt.CrossCursor)  # 默认设置为十字光标，适用于绘图
        # 设置尺寸策略
        self.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Ignored)
        # self.setScaledContents(True)

    def setOriginalPixmap(self, pixmap):
        self.originalPixmap = pixmap
        self.setPixmap(pixmap)

    def mousePressEvent(self, e):
        if self.isEnabledDrawing:
            # 获取 QLabel 和 pixmap 的尺寸
            labelSize = self.size()
            if self.pixmap() != None:
                pixmapSize = self.originalPixmap.size()
                pixmapSize.scale(labelSize, Qt.KeepAspectRatio)  # 按比例缩放
                # 计算 pixmap 在 QLabel 中的偏移量
                xOffset = (labelSize.width() - pixmapSize.width()) // 2
                yOffset = (labelSize.height() - pixmapSize.height()) // 2
                if e.x()-xOffset > 0 and e.y()-yOffset > 0 and e.x()<pixmapSize.width()+xOffset:
                    if self.shapeType == "line":
                        self.Line_list[0] = e.x()-xOffset
                        self.Line_list[1] = e.y()-yOffset
                    elif self.shapeType == "rectangle":
                        self.Rectangle_list[0] = e.x()-xOffset
                        self.Rectangle_list[1] = e.y()-yOffset
                    elif self.shapeType == "polygon":
                        self.Polygon_list.append(e.x()-xOffset)
                        self.Polygon_list.append(e.y()-yOffset)
                        self.update()

            if e.button() == Qt.RightButton:
                self.Line_list = [0, 0, 0, 0]
                self.Rectangle_list = [0, 0, 0, 0]
                self.Polygon_list.clear()
                self.setPixmap(self.originalPixmap)  # 更新QLabel的pixmap
                self.update()

    def mouseReleaseEvent(self, e):
        pass

    def mouseMoveEvent(self, e):
        if self.isEnabledDrawing:
            if self.shapeType == "line":
                self.Line_list[2] = e.x()
                self.Line_list[3] = e.y()
                self.update()
            elif self.shapeType == "rectangle":
                self.Rectangle_list[2] = e.x() - self.Rectangle_list[0]
                self.Rectangle_list[3] = e.y() - self.Rectangle_list[1]
                self.update()

    def paintEvent(self, event):
        super().paintEvent(event)
        if not self.isEnabledDrawing:
            return
        if self.pixmap() != None:
            pixmap = self.originalPixmap.copy()  # 使用原始图片的副本来绘制
            painter = QPainter(pixmap)
            # painter = QPainter(self)
            painter.begin(self)
            # 设置绘制形状的边框颜色和宽度
            pen = QPen(Qt.red, 2, Qt.SolidLine)
            painter.setPen(pen)
            if self.shapeType == "line":
                painter.drawLine(self.Line_list[0], self.Line_list[1], self.Line_list[2], self.Line_list[3])
            elif self.shapeType == "rectangle":
                painter.drawRect(self.Rectangle_list[0], self.Rectangle_list[1], self.Rectangle_list[2],
                                 self.Rectangle_list[3])
            elif self.shapeType == "polygon":
                # 设置绘制点（圆）的填充颜色
                painter.setBrush(Qt.blue)  # 设置画刷为蓝色用于填充圆
                radius = 4  # 圆的半径，用于控制点的大小
                # 绘制圆形代替点
                for i in range(0, len(self.Polygon_list), 2):
                    painter.drawEllipse(QPoint(self.Polygon_list[i], self.Polygon_list[i + 1]), radius, radius)
                # 绘制线条或多边形时，不填充颜色
                painter.setBrush(Qt.NoBrush)  # 绘制线条或多边形时不使用填充
                # 当点的数量等于4时（即两个点），绘制线条
                if len(self.Polygon_list) == 4:
                    painter.drawLine(self.Polygon_list[0], self.Polygon_list[1], self.Polygon_list[2], self.Polygon_list[3])
                # 当点的数量大于等于6时（即至少3个点），绘制多边形
                elif len(self.Polygon_list) >= 6:
                    polygon = QPolygon()
                    polygon.setPoints(*self.Polygon_list)
                    painter.drawPolygon(polygon)
            painter.end()
            self.setPixmap(pixmap)  # 更新QLabel的pixmap

    def setShapeType(self, shapeType):
        self.shapeType = shapeType
        self.points = []  # 切换图形类型时重置点列表
        self.update()

    def sizeHint(self):
        return QSize(0, 0)  # 建议大小为0,0，使得窗口可以自由缩放

    def minimumSizeHint(self):
        return QSize(0, 0)  # 最小建议大小为0,0，允许组件缩小到非常小

    def enableDrawing(self, enable):
        self.isEnabledDrawing = enable
        self.updateCursorStyle()

    def updateCursorStyle(self):
        if self.isEnabledDrawing:
            self.setCursor(Qt.CrossCursor)
        else:
            self.setCursor(Qt.ArrowCursor)
        self.update()  # Ensure the widget is updated

    def enterEvent(self, event):
        # When the mouse enters the widget, update the cursor style based on isEnabledDrawing
        self.updateCursorStyle()
        super().enterEvent(event)

    def leaveEvent(self, event):
        # Optional: Reset the cursor to the default style when the mouse leaves the widget
        # This is optional and can be adjusted based on desired behavior
        self.setCursor(Qt.ArrowCursor)
        super().leaveEvent(event)

